#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : ip_chinaz.py
@Author     : LeeCQ
@Date-Time  : 2019/12/6 13:27

"""
<<<<<<< HEAD

import requests
import re


class HttpStatusError(Exception):
    pass


class QueryIPLocation:
    """ 用IP 或者 域名 查询归属地（服务器地址查询，包含服务器提供商）：

    用requests 库请求 http://ip.tool.chinaz.com 地址获取信息，并处理；

    返回一个列表；列表中包含查询到的所有信息；[{something, ...}, ...]

    :param domain: 查询的域名或者IP
    """
    request_host = 'http://ip.tool.chinaz.com/'

    def __init__(self, domain):
        self.query_domain = domain
        self.headers = {
            'Host': 'ip.tool.chinaz.com',
            'Connection': 'keep-alive',
            'Content-Length': str(len('ip=' + self.query_domain)),
            'Cache-Control': 'max-age=0',
            'Origin': 'http://ip.tool.chinaz.com',
            'Upgrade-Insecure-Requests': '1',
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Referer': 'http://ip.tool.chinaz.com/',
            'Accept-Encoding': 'gzip, deflate',
            "Accept-Language": 'zh-CN,zh;q=0.9',
        }

    @staticmethod
    def get_url(url, data, header):
        """获取查询页面"""
        _post = requests.post(url + data, 'ip=' + data, headers=header)
        if _post.status_code == 200:
            _post.encoding = \
            [x.split('=')[1] for x in _post.headers['Content-Type'].split('; ') if x.startswith('char')][0]
            return _post.text
        else:
            return _post.status_code

    @staticmethod
    def examine_addr(text):
        """"""
        if not re.findall('<div class="col-red lh30 fz14 jspu">域名或IP解析失败</div>', text):
            return -1, 'Error', '域名或IP解析失败'

        elif not re.findall('<div class="col-red lh30 fz14 jspu">域名/IP输入有误</div>', text):
            return -1, 'Error', '域名/IP输入有误'

        else:
            return 0, 'ok'

    def re_info(self, text):
        """正则筛选页面"""
        if isinstance(text, int):
            return 'Error', '服务器错误' + str(text)

        examine = self.examine_addr(text)
        if examine[0]:
            return examine[1], examine[2]

        text = text.replace('\n', '').replace('\r', '')

        _head = re.findall('<span class=".*?">(.*?)</span>',
                           re.findall('<p class="WhwtdWrap bg-blue08 col-gray03">.(.*?).</p>', text)[0]
                           )
        _res1 = re.findall('<p class="WhwtdWrap bor-b1s col-gray03">.(.*?).</p>', text)
        _res2 = [re.findall('<span class=".*?">(.*?)</span>', _t) for _t in _res1]

        return _head, _res2

    @staticmethod
    def to_dict(head_, res_):
        """格式化输出"""
        head_ = head_ if not isinstance(head_, str) else [head_]
        res_ = res_ if not isinstance(res_, str) else [[res_], ]

        list_ = []
        for r in res_:
            list_.append({head_[i]: r[i] for i in range(0, len(head_))})
        return list_

    def start(self):
        """接口函数"""
        return self.to_dict(
            *self.re_info(
                self.get_url(
                    self.request_host + self.query_domain, self.query_domain, self.headers)
            )
        )


if __name__ == '__main__':
    from time import time
    import sys

    t = time()
    try:
        arg = sys.argv[1]
        print(arg)
    except:
        arg = input("Please feel in a Domain or IP Address: ")

    query_domain = arg
    a = QueryIPLocation(query_domain).start()
    print(a)
    print('*' * 50, '\n运行时间：', time() - t)
=======
>>>>>>> 0f663d9cdbaca672411c54e3f484639a12f0b328
